package com.ebspp.client.serverManager;

import java.util.List;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import com.ebspp.thrift.DataMsg;
import com.ebspp.thrift.GarbageCollect;
import com.ebspp.thrift.Identity;
import com.ebspp.thrift.ResourceType;

public class GarbageConnection {
	Identity id;
	String server;
	int gbPort;
	ResourceType resType;
	
	private GarbageCollect.Client gbClient;
	TTransport transport;
	
	public GarbageConnection(String server, int port, ResourceType type, Identity id)
	{
		this.gbPort = port;
		this.server = server;
		this.id = id;
		this.resType = type;
	}
	
	public void connect() throws TTransportException
	{
		transport = new TSocket(server, gbPort);
		//TTransport wTransport = new TFramedTransport(socket);
		TProtocol protocol = new TBinaryProtocol(transport);
		gbClient = new GarbageCollect.Client(protocol);
		transport.open();
	}
	public void close()
	{
		transport.close();
	}
	
	public Identity getID()
	{
		return id;
	}
	public ResourceType getResType()
	{
		return resType;
	}
	public String getServer()
	{
		return server;
	}
	
	public synchronized List<DataMsg> gbCollect(List<DataMsg> gbKeys) throws TException
	{
		return gbClient.garbageCollect(gbKeys, resType, id);
	}
	
	public boolean equals(Object obj)
	{
		if(obj == null)
			return false;
		if(obj instanceof GarbageConnection)
		{
			GarbageConnection conn = (GarbageConnection)obj;
			if(id.equals(conn.id) && server.equals(conn.server) && resType.equals(conn.resType))
				return true;
		}
		return false;
	}
	
	public int hashCode()
	{
		return id.hashCode() * 3 + server.hashCode() * 13 + resType.hashCode() * 17;
	}
}
